package artid.com.arttogo.utils;

import android.os.Environment;
import android.widget.TextView;

import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.common.Callback.Cancelable;
import org.xutils.common.task.PriorityExecutor;
import org.xutils.db.Selector;
import org.xutils.ex.DbException;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.List;

import artid.com.arttogo.app.ArtToGoApp;
import artid.com.arttogo.bean.CatalogueBean;
import artid.com.arttogo.task.CallbackSky;

public class DownloadUtil {
	private static DownloadUtil downloadUtil;
	private static Cancelable mCancelable;
	public static String baseUrl = Environment.getExternalStorageDirectory()
			+ "/YJBcatalogue/";
	public static String forderName = "/bookTemp2/mobile/index.html";
	private CallbackSky listcall;
	private CallbackSky mycall;
	public static final int NOTE_ONLINE = 1;//在线图录
	public static final int NOTE_OFFLINE = 2;//离线图录
	public static DownloadUtil getInstance() {

		if (downloadUtil == null) {
			downloadUtil = new DownloadUtil();
		}
		return downloadUtil;
	}

	public static String path = null;
	int speedProgress;
	private TextView progressContent;

	public void setTextView(TextView progressContent) {
		this.progressContent = progressContent;
	}

	public void setListCallbackSky(CallbackSky listcall) {
		this.listcall = listcall;
	}

	public void setMyCallbackSky(CallbackSky mycall) {
		this.mycall = mycall;
	}

	public String getPath() {
		return path;
	}

	/**
	 * 下载文件
	 */
	public void httpDownLoad(String path, String loadurl, boolean firstbo) {
		this.path = path;
		// mCancelable = null;
		RequestParams params = new RequestParams(loadurl);
		params.setSaveFilePath(path);// 自定义文件保存路径
		params.setAutoRename(false);// 开启自动命名文件，其实就是同过URL拿到你文件名称
		params.setCancelFast(true);// 是否可以被立即停止.
		params.setExecutor(new PriorityExecutor(0, false));
		if (mCancelable == null)
			mCancelable = x.http().request(HttpMethod.GET, params,
					new Callback.ProgressCallback<File>() {

						@Override
						public void onCancelled(CancelledException cex) {
							// TODO Auto-generated method stub
							System.out.println("主动停止网络请求");
						}

						@Override
						public void onError(Throwable ex, boolean isOnCallback) {
							// TODO Auto-generated method stub
							// 请求错误
							if (isOnCallback == false) {
								// ex异常信息不是来自回调方法
								System.out.println("ex异常信息不是来自回调方法："
										+ ex.getMessage());
							} else {
								// ex异常信息是来自回调方法
								System.out.println("ex异常信息是来自回调方法："
										+ ex.getMessage())   ;
							}
						}

						@Override
						public void onFinished() {
							// TODO Auto-generated method stub
							System.out.println("请求完毕,不管成功失败");
						}

						@Override
						public void onSuccess(File result) {
							// TODO Auto-generated method stub
							System.out.println("当前文件下载完成:"
									+ fileIsExists(downloadUtil.path));
							if (fileIsExists(downloadUtil.path)) {
								if (mycall != null)
									mycall.callBack();
								if (listcall != null)
									listcall.callBack();
								downloadUtil.path = null;
								try {
									DbManager db = x.getDb(((ArtToGoApp) ArtToGoApp
											.getActivity().getApplication())
											.getDaoConfig());
									// CatalogueBean cata = new CatalogueBean();
									// cata.setLocalurl(downloadUtil.path);
									// cata.setOnload(true);
									// db.update(cata, "onload");
									List<CatalogueBean> all = null;
									// 输入0查询全部
									Selector<CatalogueBean> selector = db
											.selector(CatalogueBean.class);
									// 如果要使用条件查询的话可以使用
									// Selector<user> selector =
									// db.selector(User.class).where("id","=",id).and("age",">",10);
									all = selector.findAll();
									for (int i = 0; i < all.size(); i++) {
										CatalogueBean cb = all.get(i);
										if (!fileIsExists(cb.getLocalurl())) {
											httpDownLoad(cb.getLocalurl(),
													cb.getZipurl(), false);
											
											break;
										}
									}

								} catch (DbException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}

						}

						@Override
						public void onLoading(final long total,
								final long current, boolean isDownloading) {
							// TODO Auto-generated method stub
							// 下载时被调用的方法
							System.out.println("当前文件总大小：" + total + "\n"
									+ "当前下载进度：" + current + "\n" + "当前是否在下载："
									+ isDownloading);
							speedProgress = (int) (current * 100 / total);
							if (progressContent != null) {
								progressContent.setText(speedProgress + "%");

							}
						}

						@Override
						public void onStarted() {
							// TODO Auto-generated method stub
							// 网络请求开始被回调的方法
							System.out.println("网络请求开始");
						}

						@Override
						public void onWaiting() {
							// TODO Auto-generated method stub
							// 网络请求之前最先被调用的方法
							System.out.println("网络请求开始开始之前");
						}
					});
//		if (mycall != null)
//			mycall.callBack();
//		if (listcall != null)
//			listcall.callBack();
		
	}

	public void cancelableCancel() {
		mCancelable.cancel();
		mCancelable = null;
		DbManager db = x.getDb(((ArtToGoApp) ArtToGoApp.getActivity().getApplication())
				.getDaoConfig());
		CatalogueBean cata = new CatalogueBean();
		cata.setLocalurl(path);
		cata.setProgress(String.valueOf(speedProgress));
		try {
			db.update(cata, "progress");
		} catch (DbException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		this.path = null;
	}

	public boolean fileIsExists(String path) {
		try {
			File f = new File(path);
			if (!f.exists()) {
				return false;
			}

		} catch (Exception e) {
			// TODO: handle exception
			return false;
		}
		return true;
	}
}
